import requests
import logging
from django.conf import settings

logger = logging.getLogger(__name__)

class K8SService:
    def __init__(self):
        self.base_url = settings.FASTAPI_BASE_URL
    
    def create_namespace(self, namespace_name):
        """创建命名空间"""
        try:
            # 确保命名空间名称符合Kubernetes规范
            namespace_name = self._sanitize_namespace_name(namespace_name)
            
            url = f"{self.base_url}/api/v1/namespaces/"
            payload = {"name": namespace_name}
            response = requests.post(url, json=payload, timeout=30)
            
            # 记录详细的错误信息
            if response.status_code != 200:
                logger.error(f"代码非200 详细信息: Status={response.status_code}, Response={response.text}")
            
            return response.json(), response.status_code
        except requests.exceptions.RequestException as e:
            logger.error(f"创建命名空间请求失败: {e}")
            return {"error": str(e)}, 500
    
    def _sanitize_namespace_name(self, name):
        """清理命名空间名称，确保符合Kubernetes规范"""
        # 转换为小写
        name = name.lower()
        # 替换非法字符
        name = name.replace('_', '-')
        # 移除开头和结尾的连字符
        name = name.strip('-')
        # 限制长度
        if len(name) > 63:
            name = name[:63].rstrip('-')
        return name
    


    
    def delete_namespace(self, namespace_name):
        """删除命名空间"""
        try:
            url = f"{self.base_url}/api/v1/namespaces/{namespace_name}"
            response = requests.delete(url, timeout=30)
            return response.json(), response.status_code
        except requests.exceptions.RequestException as e:
            logger.error(f"删除命名空间失败: {e}")
            return {"error": str(e)}, 500
    
    def list_namespaces(self):
        """列出所有命名空间"""
        try:
            url = f"{self.base_url}/api/v1/namespaces/"
            response = requests.get(url, timeout=30)
            return response.json(), response.status_code
        except requests.exceptions.RequestException as e:
            logger.error(f"获取命名空间列表失败: {e}")
            return {"error": str(e)}, 500
    
    def get_namespace(self, namespace_name):
        """获取特定命名空间"""
        try:
            url = f"{self.base_url}/api/v1/namespaces/{namespace_name}"
            response = requests.get(url, timeout=30)
            return response.json(), response.status_code
        except requests.exceptions.RequestException as e:
            logger.error(f"获取命名空间失败: {e}")
            return {"error": str(e)}, 500

# 全局实例
k8s_service = K8SService()